package redisv9ex

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/gobase/getfrom"
	"github.com/redis/go-redis/v9"
)

func getRedisFrom1(objref *gobase.ObjectInnerRef, args gobase.StrMap) (data []byte, err error) {
	clt := objref.GetObject().(*redis.Client)
	opera := NewRedisOperator(clt)
	defer func() {
		opera.clt = nil
	}()
	key := args["key"]
	field := args["field"]
	if len(field) > 0 {
		val, e := opera.HStringByName(key, field)
		if e != nil {
			return nil, err
		}
		return []byte(val), nil
	} else {
		val := opera.StringByName(key, "")
		return []byte(val), nil
	}
}

// user=xxx&pass=&addr=&key=
func getRedisFrom(args ...interface{}) (data []byte, err error) {
	if len(args) <= 0 {
		return nil, fmt.Errorf("invalid param")
	}

	confMap, ok := args[0].(gobase.StrMap)
	if !ok {
		if str, ok1 := args[0].(string); ok1 {
			confMap = gobase.NewStrMap()
			confMap.URLFormDecode(str)
		}
	}
	if confMap != nil {
		if len(confMap) == 0 {
			return nil, fmt.Errorf("Acquisition failed! invalid args!")
		}
		if _, ok0 := confMap["addr"]; !ok0 {
			if v, ok1 := confMap["connstr"]; ok1 {
				confMap["addr"] = v
			}
		}
		s0 := confMap.URLEncode0WithKeys("addr", "pass", "user", "connrand", "cluster")
		objref := DefaultRedisClient.CheckGetRef(s0)
		defer objref.ReleaseRef()
		return getRedisFrom1(objref, confMap)
	}

	if objref, ok1 := args[0].(*gobase.ObjectInnerRef); ok1 && len(args) > 1 {
		confMap = gobase.NewStrMap()
		confMap.URLFormDecode(args[1].(string))
		return getRedisFrom1(objref, confMap)
	}
	return nil, fmt.Errorf("invalid args...")
}

func init() {
	getfrom.Register("redisclt", getRedisFrom)
}
